package leetcode_动态规划._07背包问题._01背包;

/**
 * @author yzh
 * @data 2021/3/18 14:00
 */
public class Sample {
    public static void main(String[] args) {
        int[] w = {1, 3, 4};
        int[] p = {15, 20, 30};
        int bg = 4;
        System.out.println(new Sample().method2(w, p, bg));
    }

    // 先遍历物品，再遍历背包容量
    public int method1(int[] w, int[] p, int bg) {
        // int[][] dp = new int[w.length][bg + 1];
        int[] dp = new int[bg + 1];
        for (int i = 0; i < w.length; i++) {
            for (int j = bg; j >= w[i]; --j) {
                // dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - w[i]] + p[i]);
                dp[j] = Math.max(dp[j], dp[j - w[i]] + p[i]);
            }
        }
        return dp[bg];
    }

    // 先遍历背包容量，再遍历物品
    public int method2(int[] w, int[] p, int bg) {
        int[] dp = new int[bg + 1];
        for(int j = 1; j <= bg; j++) { // 遍历背包容量
            for(int i = 0; i < w.length; i++) { // 遍历物品
                if (j >= w[i]) {
                    dp[j] = Math.max(dp[j], dp[j - w[i]] + p[i]);
                }
            }
        }
        return dp[bg];
    }

}
